//
//  AppDelegate.swift
//  DollarBuy
//
//  Created by 郑东喜 on 2016/11/1.
//  Copyright © 2016年 郑东喜. All rights reserved.
//

import UIKit
// iOS 10+ notificaiton
import UserNotifications

var netStatus = ""


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,UIAlertViewDelegate {
    
    var window: UIWindow?
    
    let tool = WXTool()
    let qqTool = QQTool()
    
    lazy var tencentOAuth = TencentOAuth()
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        //创建window
        UIApplication.shared.isStatusBarHidden = false

        ///设置主启动界面
        setMainBar()

        //阿里云推送
        
        self.startAlipush()
        
        registerAPNs(application)
        
        // 点击通知将App从关闭状态启动时，将通知打开回执上报
        //CloudPushSDK.handleLaunching(launchOptions)(Deprecated from v1.8.1)
        CloudPushSDK.sendNotificationAck(launchOptions)
        return true
    }
}


// MARK:- 设置主控制器
extension AppDelegate {
    func setMainBar() -> Void {
        // 创建window
//        window = UIWindow(frame: CGRect.init(x: 0, y: 20, width: SW, height: SH - 20))
        
        window = UIWindow.init(frame: UIScreen.main.bounds)
        
        window?.makeKeyAndVisible()

        
        
        let customtabbar = MainViewController()
        window?.rootViewController = customtabbar
        
        //设置QQ
        setQQ()
        
        //设置微信
        setWX()
        
        //友盟
        umCollecData()
        
        // 设置全局颜色
        UITabBar.appearance().tintColor = commonBtnColor
        UINavigationBar.appearance().tintColor = commonBtnColor
    }
}

// MARK:- 友盟数据统计
extension AppDelegate {
    
    /// 友盟统计
    func umCollecData() -> Void {
        let UMConfigInstance = UMAnalyticsConfig.sharedInstance()
        UMConfigInstance?.appKey = UMENG_APPKEY
        UMConfigInstance?.channelId = "App Store"
        MobClick.start(withConfigure: UMConfigInstance)
        
        //设置app版本号
        let infoDictionary = Bundle.main.infoDictionary!
        if let version = infoDictionary["CFBundleShortVersionString"]{
            MobClick.setAppVersion(version as! String)
        }
        //打印log日志
        MobClick.setLogEnabled(false)
    }
}

// MARK:- 第三方介入
extension AppDelegate {
    func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
                
        let wxUrl = String(format: "%@", arguments: [WXPatient_App_ID])
        let qqUrl = String(format: "tencent%@", arguments: [QQAppID])
        
        if url.absoluteString.hasPrefix(wxUrl) {
            return WXApi.handleOpen(url, delegate: tool)
            
        } else if url.absoluteString.hasPrefix(qqUrl){
            QQApiInterface.handleOpen(url, delegate: qqTool)
            return TencentOAuth.handleOpen(url)
            //微信支付
        }
            
        else if url.host == "safepay" {
            // 支付跳转支付宝钱包进行支付，处理支付结果
            
            AlipaySDK.defaultService().processOrder(withPaymentResult: url, standbyCallback: {[weak self] (resultDic) in
                
                var data = NSDictionary()
                
                if let resultStatus = resultDic?["resultStatus"] as? String {
                    
                    if resultStatus == "9000"{
                        data = ["re" : "支付成功"]
                        
                    }else if resultStatus == "8000"{
                        data = ["re" : "正在处理中"]
                        
                    }else if resultStatus == "4000"{
                        data = ["re" : "订单支付失败"]
                        
                    }else if resultStatus == "6001" {
                        data = ["re" : "用户中途取消"]
                        
                    } else if resultStatus == "6002" {
                        data = ["re" : "网络连接出错"]
                    }
                }
                
                //发出网页调用支付宝的结果
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: "123"), object: self, userInfo: data as? [AnyHashable : Any])
                
                return
            })
        }
//            
//        else if url.scheme == WXPatient_App_ID {
//            return WXApi.handleOpen(url, delegate: tool)
//        }
        return true
    }
    
}

// MARK:- QQ、微信第三方回调
extension AppDelegate {

    // MARK:- 微信、QQ回调代理方法
    func application(_ application: UIApplication, handleOpen url: URL) -> Bool {
                
        let wxUrl = String(format: "%@", arguments: [WXPatient_App_ID])
        let qqUrl = String(format: "tencent%@", arguments: [QQAppID])
        
        //微信
        if url.absoluteString.hasPrefix(wxUrl) {
            
            
            return WXApi.handleOpen(url, delegate: tool)
            
            //QQ
        } else if url.absoluteString.hasPrefix(qqUrl){
            QQApiInterface.handleOpen(url, delegate: qqTool)
            return TencentOAuth.handleOpen(url)
        }
        return true;
    }
    
    
    func applicationDidEnterBackground(_ application: UIApplication) {
        MBManager.hideAlert()
    }
}

// MARK:- 微信
extension AppDelegate {
    
    func setWX() -> Void {
        WXApi.registerApp(WXPatient_App_ID)
//        WXApi.registerApp(WXPatient_App_ID, enableMTA: true)

    }
}

// MARK:- QQ
extension AppDelegate {
    func setQQ() -> Void {
        tencentOAuth = TencentOAuth(appId: QQAppID, andDelegate: qqTool)
    }
}

// MARK:- 开始启动阿里推送
extension AppDelegate {
    fileprivate func startAlipush() -> Void {
        
        // 初始化阿里云推送SDK
        initCloudPushSDK()
        
        // 监听推送通道打开动作
        listenOnChannelOpened()
        
        // 监听推送消息到达
        registerMessageReceive()
    }
}

// MARK:- 阿里云推送实现的方法
extension AppDelegate : UNUserNotificationCenterDelegate {
    // 向APNs注册，获取deviceToken用于推送
    func registerAPNs(_ application: UIApplication) {
        if #available(iOS 10, *) {
            // iOS 10+
            let center = UNUserNotificationCenter.current()
            // 创建category，并注册到通知中心
            createCustomNotificationCategory()
            center.delegate = self
            // 请求推送权限
            center.requestAuthorization(options: [.alert, .badge, .sound], completionHandler: { (granted, error) in
                if (granted) {
                    // User authored notification
                    print("User authored notification.")
                    // 向APNs注册，获取deviceToken
                    application.registerForRemoteNotifications()
                } else {
                    // User denied notification
                    print("User denied notification.")
                }
            })
        } else if #available(iOS 8, *) {
            // iOS 8+
            application.registerUserNotificationSettings(UIUserNotificationSettings.init(types: [.alert, .badge, .sound], categories: nil))
            application.registerForRemoteNotifications()
        } else {
            // < iOS 8
            application.registerForRemoteNotifications(matching: [.alert,.badge,.sound])
        }
        
    }
    
    
    // 创建自定义category，并注册到通知中心
    @available(iOS 10, *)
    func createCustomNotificationCategory() {
        let action1 = UNNotificationAction.init(identifier: "action1", title: "test1", options: [])
        let action2 = UNNotificationAction.init(identifier: "action2", title: "test2", options: [])
        let category = UNNotificationCategory.init(identifier: "test_category", actions: [action1, action2], intentIdentifiers: [], options: UNNotificationCategoryOptions.customDismissAction)
        UNUserNotificationCenter.current().setNotificationCategories([category])
    }
    
    // 初始化推送SDK
    func initCloudPushSDK() {
        // 打开Log，线上建议关闭
        //        CloudPushSDK.turnOnDebug()
        CloudPushSDK.asyncInit(alipushKey, appSecret: alipushAppSecret) { (res) in
            if (res!.success) {
//                print("Push SDK init success, deviceId: \(CloudPushSDK.getDeviceId()!)")
                XFLog(message: "device ID \(CloudPushSDK.getDeviceId())")
            } else {
//                print("Push SDK init failed, error: \(res!.error!).")
                XFLog(message: "Push SDK init failed, error: \(res!.error!).")
            }
        }
        
    }
    
    // 监听推送通道是否打开
    func listenOnChannelOpened() {
        let notificationName = Notification.Name("CCPDidChannelConnectedSuccess")
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(channelOpenedFunc(notification:)),
                                               name: notificationName,
                                               object: nil)
        
    }
    
    func channelOpenedFunc(notification : Notification) {
//        print("Push SDK channel opened.")
        XFLog(message: "Push SDK channel opened.")
    }
    
    // 注册消息到来监听
    func registerMessageReceive() {
        let notificationName = Notification.Name("CCPDidReceiveMessageNotification")
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(onMessageReceivedFunc(notification:)),
                                               name: notificationName,
                                               object: nil)
        
    }
    
    // 处理推送消息
    func onMessageReceivedFunc(notification : Notification) {
//        print("Receive one message.")
        
        XFLog(message: "Receive one message.")
        let pushMessage: CCPSysMessage = notification.object as! CCPSysMessage
        let title = String.init(data: pushMessage.title, encoding: String.Encoding.utf8)
        let body = String.init(data: pushMessage.body, encoding: String.Encoding.utf8)
        
        
        let alVC : UIAlertController = UIAlertController.init(title: title as String?, message: body as String?, preferredStyle: .alert)
        
        alVC.addAction(UIAlertAction.init(title: "好的", style: .default, handler: nil))
        
        
        DispatchQueue.main.async {
            UIApplication.shared.keyWindow?.rootViewController?.present(alVC, animated: true, completion: nil)
        }
        
//        print("Message title: \(title!), body: \(body!).")
        XFLog(message: "Message title: \(title!), body: \(body!).")
    }
    
    // App处于启动状态时，通知打开回调（< iOS 10）
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        print("Receive one notification.")
        let aps = userInfo["aps"] as! [AnyHashable : Any]
        let alert = aps["alert"] ?? "none"
        let badge = aps["badge"] ?? 0
        let sound = aps["sound"] ?? "none"
        let extras = userInfo["Extras"]
        
        completionHandler(.newData)
        
        XFLog(message: "\((#file as NSString).lastPathComponent):(\(#line))\n",file: "Notification, alert: \(alert), badge: \(badge), sound: \(sound), extras: \(extras).")
    }
    
    // 处理iOS 10通知(iOS 10+)
    @available(iOS 10.0, *)
    func handleiOS10Notification(_ notification: UNNotification) {
        let content: UNNotificationContent = notification.request.content
        let userInfo = content.userInfo
        // 通知时间
        let noticeDate = notification.date
        // 标题
        let title = content.title
        // 副标题
        let subtitle = content.subtitle
        // 内容
        let body = content.body
        // 角标
        let badge = content.badge ?? 0
        // 取得通知自定义字段内容，例：获取key为"Extras"的内容
        let extras = userInfo["Extras"]
        // 通知打开回执上报
        CloudPushSDK.sendNotificationAck(userInfo)

        XFLog(message: "Notification, date: \(noticeDate), title: \(title), subtitle: \(subtitle), body: \(body), badge: \(badge), extras: \(extras).")
    }
    
    // App处于前台时收到通知(iOS 10+)
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

        XFLog(message: "Receive a notification in foreground.")
        handleiOS10Notification(notification)
        // 通知不弹出
        completionHandler([])
        // 通知弹出，且带有声音、内容和角标
        //completionHandler([.alert, .badge, .sound])
    }
    
    // 触发通知动作时回调，比如点击、删除通知和点击自定义action(iOS 10+)
    @available(iOS 10, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let userAction = response.actionIdentifier
        if userAction == UNNotificationDefaultActionIdentifier {

            XFLog(message: "User opened the notification.")
            // 处理iOS 10通知，并上报通知打开回执
            handleiOS10Notification(response.notification)
        }
        
        if userAction == UNNotificationDismissActionIdentifier {
            XFLog(message: "User dismissed the notification.")
        }
        
        let customAction1 = "action1"
        let customAction2 = "action2"
        if userAction == customAction1 {
            print("User touch custom action1.")
        }
        
        if userAction == customAction2 {
            print("User touch custom action2.")
        }
        
        completionHandler()
    }
    
    // APNs注册成功
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        print("Get deviceToken from APNs success.")
        CloudPushSDK.registerDevice(deviceToken) { (res) in
            if (res!.success) {
                XFLog(message: "Upload deviceToken to Push Server, deviceToken: \(CloudPushSDK.getApnsDeviceToken()!)")
            } else {

                XFLog(message: "Upload deviceToken to Push Server failed, error: \(res?.error)")
            }
        }
    }
    
    // APNs注册失败
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        XFLog(message: "Get deviceToken from APNs failed, error: \(error).")
    }
    
    // 禁止横屏
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        return UIInterfaceOrientationMask.portrait;
    }
   
}
